﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Framework.Platform.Components.UI.Authentication;

namespace Framework.Platform.Components
{
    public class MainApplicationContext : ApplicationContext
    {
        private ILoginUI _LoginUI;

        public ILoginUI LoginUI
        {
            get { return _LoginUI; }
            set { _LoginUI = value; }
        }

        private IApplicationMainUI _ApplicationMainUI;

        public IApplicationMainUI ApplicationMainUI
        {
            get { return _ApplicationMainUI; }
            set { _ApplicationMainUI = value; }
        }

        private IAuthentication _Authentication;

        public IAuthentication Authentication
        {
            get { return _Authentication; }
            set { _Authentication = value; }
        }

        private bool _ShouldRun = true;

        /// <summary>
        /// Gets if the main application should run.
        /// </summary>
        public bool ShouldRun
        {
            get
            {
                return this._ShouldRun;
            }
        }

        /// <summary>
        /// Initializes a new instance of the MainApplicationContext class.
        /// </summary>
        public MainApplicationContext()
        {
        }

        public void Init()
        {
            try
            {
                this.LoginUI.Submit += new EventHandler<LoginUISubmitEventArgs>(LoginForm_Submit);
                this.LoginUI.Cancel += new EventHandler<EventArgs>(LoginUI_Cancel);
                this.ApplicationMainUI.ApplicationClosed += new EventHandler<EventArgs>(ApplicationMainUI_ApplicationClosed);
                
                try
                {
                    this.LoginUI.ShowUI();
                }
                catch
                {
                    throw;
                }
            }
            catch
            {
                this._ShouldRun = false;
                throw;
            }
        }

        void ApplicationMainUI_ApplicationClosed(object sender, EventArgs e)
        {
            this.ExitThread();
        }

        void LoginUI_Cancel(object sender, EventArgs e)
        {
            this._ShouldRun = false;
            this.ExitThread();
        }

        void LoginForm_Submit(object sender, LoginUISubmitEventArgs e)
        {
            try
            {
                this.Authentication.Authenticate(e.UserName, e.Password);
                this.LoginUI.HideUI();
                this.ApplicationMainUI.ShowUI();
                this._ShouldRun = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void formMain_FormClosed(object sender, System.EventArgs e)
        {
            this.ExitThread();
        }
    }
}
